package com.starsea.book.ui.newpage.utils

import android.app.Activity
import android.app.ActivityManager
import android.content.Context
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.util.Stack

/**
 * @author Lee
 * @createTime 2023-07-27 15 GMT+8
 * @desc :
 */
class AppManager {

    /**
     * Actvity存储栈
     */
    private var mActivityStack: Stack<Activity?>? = null


    constructor() {
        if (mActivityStack == null) {
            mActivityStack = Stack()
        }
    }

    companion object {
        /**
         * AppManager单例对象
         */
        @Volatile
        private var mAppManager: AppManager? = null

        /**
         * 单一实例
         */
        fun getInstance(): AppManager {
            if (mAppManager == null) {
                synchronized(AppManager::class.java) {
                    if (mAppManager == null) mAppManager = AppManager()
                }
            }
            return mAppManager!!
        }
    }


    /**
     * 获取栈顶Activity（堆栈中最后一个压入的）
     */
    fun currentActivity(): AppCompatActivity? {
        return mActivityStack!!.lastElement() as AppCompatActivity?
    }


    /**
     * 添加Activity到堆栈
     */
    fun addActivity(activity: Activity?) {
        if (mActivityStack == null) {
            mActivityStack = Stack()
        }
        if (activity == null) {
            return
        }
        if (!existActivity(activity::class.java.name))
            mActivityStack!!.add(activity)
    }

    /**
     * 获取栈顶Activity（堆栈中最后一个压入的）
     */
    fun getTopActivity(): Activity? {
        return mActivityStack!!.lastElement()
    }

    /**
     * 结束栈顶Activity（堆栈中最后一个压入的）
     */
    fun killTopActivity() {
        val activity = mActivityStack!!.lastElement()
        killActivity(activity)
    }

    /**
     * 结束指定的Activity
     */
    fun killActivity(activity: Activity?) {
        if (activity != null) {
            mActivityStack!!.remove(activity)
            activity.finish()
        }
    }

    /**
     * 结束指定类名的Activity
     */
    @Synchronized
    fun killActivity(vararg calsses: Class<*>) {
        if (mActivityStack == null || mActivityStack!!.isEmpty()) return
        val activities: MutableList<Activity?> = ArrayList()
        for (cls in calsses) {
            for (activity in mActivityStack!!) {
                if (activity!!.javaClass == cls) {
                    activities.add(activity)
                }
            }
        }
        for (activity in activities) {
            killActivity(activity)
        }
    }

    /**
     * 结束除了当前的其他所有Activity
     */
    @Synchronized
    fun killOtherExitThisActivity(calsses: Class<*>) {
        if (mActivityStack == null || mActivityStack!!.isEmpty()) return
        var i = 0
        val size = mActivityStack!!.size
        while (i < size) {
            if (null != mActivityStack!![i]) {
                if (mActivityStack!![i]!!.javaClass != calsses) mActivityStack!![i]!!.finish()
            }
            i++
        }
    }

    /**
     * 结束所有Activity
     */
    fun killAllActivity() {
        if (mActivityStack == null || mActivityStack!!.isEmpty()) {
            return
        }
        var i = 0
        val size = mActivityStack!!.size
        while (i < size) {
            if (null != mActivityStack!![i]) {
                mActivityStack!![i]!!.finish()
            }
            i++
        }
        mActivityStack!!.clear()
    }

    /**
     * 结束除了当前的其他所有Activity
     *
     * @param activity
     */
    fun killOthersActivity(activity: Activity?) {
        if (activity == null) {
            return
        }
        var i = 0
        val size = mActivityStack!!.size
        while (i < size) {
            if (null != mActivityStack!![i] && activity !== mActivityStack!![i]) {
                mActivityStack!![i]!!.finish()
            }
            i++
        }
        mActivityStack!!.clear()
        mActivityStack!!.add(activity)
    }

    /**
     * 判断Activity是否存在
     *
     * @param className
     * @return
     */
    fun existActivity(className: String): Boolean {
        val activity = getActivityByName(className)
        return activity != null && !activity.isFinishing
    }

    /**
     * 根据名字查找Activity
     *
     * @param className
     * @return
     */
    fun getActivityByName(className: String): Activity? {
        var activity: Activity? = null
        var i = 0
        val size = mActivityStack!!.size
        while (i < size) {
            if (null != mActivityStack!![i]) {
                if (mActivityStack!![i]!!.javaClass.name == className) {
                    activity = mActivityStack!![i]
                }
            }
            i++
        }
        return activity
    }

    /**
     * 删除并结束掉Activity
     *
     * @param activity
     */
    fun finishActivity(activity: Activity?) {
        var pos = -1
        if (activity != null && mActivityStack != null) {
            var i = 0
            val size = mActivityStack!!.size
            while (i < size) {
                if (null != mActivityStack!![i]) {
                    if (activity === mActivityStack!![i]) {
                        pos = i
                        activity.finish()
                    }
                }
                i++
            }
            if (pos != -1) {
                mActivityStack!!.removeAt(pos)
            }
        }
    }

    /**
     * 从栈里删除activity
     *
     * @param activity
     */
    fun remove(activity: Activity?) {
        if (activity != null && mActivityStack != null) {
            mActivityStack!!.remove(activity)
        }
    }

    /**
     * 退出应用程序
     */
    fun AppExit(context: Context) {
        try {
            killAllActivity()
            val activityMgr = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            activityMgr.restartPackage(context.packageName)
            System.exit(0)
        } catch (e: Exception) {
        }
    }

    fun dynamicAuthority(abActivity: Activity?, permission: String, returnValue: Int): Boolean {
        return if (ContextCompat.checkSelfPermission(abActivity!!, permission)
            != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(abActivity, arrayOf(permission), returnValue)
            false
        } else {
            true
        }
    }

    fun getSmallBitmap(filePaht: String?): Bitmap? {
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = true
        BitmapFactory.decodeFile(filePaht, options)
        options.inSampleSize = calculateInSampleSize(options, 480, 800)
        options.inJustDecodeBounds = false
        return BitmapFactory.decodeFile(filePaht, options)
    }

    fun calculateInSampleSize(options: BitmapFactory.Options, reqWidth: Int, reqHeight: Int): Int {
        val height = options.outHeight
        val width = options.outWidth
        var inSampleSize = 1
        if (height > reqHeight || width > reqWidth) {
            val heightRatio = Math.round(height.toFloat() / reqHeight.toFloat())
            val widthRatio = Math.round(width.toFloat() / reqWidth.toFloat())
            inSampleSize = if (heightRatio < widthRatio) heightRatio else widthRatio
        }
        return inSampleSize
    }

    fun compressBmpToFile(bmp: Bitmap, file: File?) {
        val baos = ByteArrayOutputStream()
        var options = 80 //个人喜欢从80开始,
        bmp.compress(Bitmap.CompressFormat.JPEG, options, baos)
        while (baos.toByteArray().size / 1024 > 100) {
            baos.reset()
            options -= 10
            bmp.compress(Bitmap.CompressFormat.JPEG, options, baos)
        }
        try {
            val fos = FileOutputStream(file)
            fos.write(baos.toByteArray())
            fos.flush()
            fos.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}